#!/usr/bin/env python

import sys
import urlparse
import urllib2
import re
import base64
from BeautifulSoup import BeautifulSoup


def load_results(url):
    results = {}

    try:
        for line in file(base64.b32encode(url), 'rb'):
            key, name, passed, not_run, failed = line.split()
            results[key] = [int(name), int(passed), int(not_run), int(failed)]
    except:
        pass

    return results


def main(args):

    
    result_page_regexp = re.compile(r'log([0-9]+)L([^"]+)')

    top_url = args[0]
    product = top_url.split('/')[-1]
    
    results = load_results(top_url)
    try:
        for line in  urllib2.urlopen(top_url):
            m = result_page_regexp.search(line)
            if m:
                key = m.group(1)
                if key in results:
                    continue
                name = int(m.group(2).split('_')[-1][5:])

                print 'loading stats for', name
                artifacts_url = urlparse.urljoin(top_url, '../../artifacts/' + product + '/' + key + '/win32/')
                try:
                    soup = BeautifulSoup(urllib2.urlopen(artifacts_url).read())
                except:
                    continue
                passed = 0
                not_run = 0
                failed = 0
                for a in  soup.findAll('a'):
                    if a['href'].endswith('.xml'):
                        test_results = BeautifulSoup(urllib2.urlopen(urlparse.urljoin(top_url, a['href'])).read())
                        suite = test_results.find('testsuite')
                        passed += int(suite['tests'])
                        not_run += int(suite['not-run'])
                        failed += int(suite['failures'])



                results[key] = [name, passed, not_run, failed]
    finally:
        f = file(base64.b32encode(top_url), 'wb')
        for key in results:
            output = ' '.join([str(i) for i in results[key]])
            f.write(key)
            f.write(' ')
            f.write(output)
            f.write('\n')

    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

